<template>

	<view class="root">

		<view v-if="loaded" :class="hasComment ? 'blog-container' : 'blog-margin-container' " :key="blog.id">
			<image :src="blog.user.avatar" mode="aspectFill" class="img-head"></image>
			<text class="blog-title">{{blog.title}}</text>
			<text class="blog-author">{{blog.user.nickName}}@{{blog.createTime}}</text>
			<rich-text :nodes="blog.content" class="item-content"></rich-text>
			<text class="iconfont icon-shoucang img-oper" @click.stop="popSheet(blog.id)"></text>
			<view>
				<text v-for="(tag,idx) in blog.tags" class="item-tag">{{tag}}</text>
			</view>

			<view class="icon-container">
				<text @click.stop="changeGood(blog,false)" v-if="!hasGood" class="iconfont icon-blackzan icon"></text>
				<text @click.stop="changeGood(blog,true)" v-else class="iconfont icon-smailzan icon"></text>
				<text class="icon-text">{{blog.good}}</text>
				<!-- ------------------ -->
				<!-- <text @click.stop="changeGood(blog.id,false)" v-if="!hasGood"
					class="iconfont icon-smailzan icon"></text>
				<text @click.stop="changeGood(blog.id,true)" v-else class="iconfont icon-blackzan icon"></text>
				<text class="icon-text">{{blog.good}}</text>
 -->
				<text class="iconfont icon-pinglun icon"></text>
				<text class="icon-text">{{blog.comments.length}}</text>
				<text class="iconfont icon-yueduxiao icon"></text>
				<text class="icon-text">{{blog.readCount}}</text>
			</view>
		</view>






		<view v-if="hasComment" class="blog-margin-container">
			<view v-for="(item,index) in parents" :key="item.id">
				<view class="parent-container">
					<text class="cmt-author">{{item.nickName}}</text>
					<view class="cmt-time-container">
						<text class="cmt-time">{{item.createTime}}</text>
						<text v-if="canDelete(item)" class="txt-delete"
							@click.stop="deleteCmt(item,true,index)">[删除]</text>
					</view>
					<image :src="item.avatar" mode="aspectFill" class="cmt-avatar"></image>
					<text class="cmt-content" @click="clickToReply(item)">{{item.content}}</text>
				</view>
				<view v-if="replies[index].length>0" class="replies-container"></view>
				<view v-for="(reply,idx) in replies[index]" :key="reply.id" class="reply-item">

					<view class="reply-info">
						<text class="reply-author">{{reply.nickName}}:</text>
						<text class="reply-to">@{{reply.toUser}}</text>
						<text class="reply-time">{{reply.createTime}}</text>
						<text v-if="canDelete(reply)" class="txt-delete"
							@click.stop="deleteCmt(reply,false,index)">[删除]</text>
					</view>
					<text class="reply-content" @click="clickToReply(reply)">{{reply.content}}</text>
				</view>
				<view v-if="index < parents.length - 1" class="cmt-line"></view>
			</view>

		</view>




		<view class="input-container">
			<image :src="userAvatar" mode="aspectFill" class="input-avatar" @click.stop="onLogin()"></image>
			<textarea auto-height v-model="inputValue" :placeholder="inputHolder" class="input-area"
				placeholder-class="input-holder" @input="inputGetValue" />
			<image src="../../static/commit.png" class="input-commit" @click="pushCmtValue"></image>
		</view>

		<login-dialog ref="shell" @afterLogin="afterLogin"></login-dialog>


		</login-dialog>

	</view>

</template>

<script>
	import {
		stdout,
		title
	} from 'process';
	let cmtValue = "";
	let parentId = null;
	let app = getApp()
	export default {
		data() {
			return {
				id: "",
				blog: [],
				good_ids: [],
				hasGood: false,
				loaded: false,
				parents: [],
				replies: [],
				hasComment: false,
				inputValue: "",
				inputHolder: "请输入内容",
				userAvatar: "../../static/default_user.png"
			}
		},
		onLoad(options) {
			let id = options.id
			let good_ids = uni.getStorageSync(this.$params.key_good_ids)
			if (good_ids) {
				this.hasGood = good_ids.indexOf(id) >= 0
			}
			this.addReadCount(id)
			this.$noti.add(this.$params.noti_login_status, this.afterLogin, this)

		},
		onUnload() {
			this.$noti.remove(this.$params.noti_login_status, this)
		},
		mounted() {
			if (!app.globalData.token == 0) {
				this.userAvatar = this.$params.host + getApp().globalData.avatar;
			}

		},
		methods: {
			deleteCmt(cmt, isParent, index) {
				let url = this.$params.host + this.$params.action_blogs_del_comment + cmt.id
				let data = {
					token: app.globalData.token
				}
				uni.showModal({
					title: '删除评论',
					content: '确定删除该评论吗\n注意,子评论也会同时删除',
					showCancel: true,
					cancelText: '算了',
					confirmText: '删除',
					success: res => {
						if (res.confirm) {
							uni.showLoading({
								title: '删除评论......',
								mask: false
							});
							this.$request.deleteParams(url, data, res => {
								uni.showToast({
									title: res.message,
									icon: "none"
								});
								if (res.success) {
									if (isParent) {
										let list = this.replies[index]
										list.push(this.parents[index])
										this.$util.remove(this.parents, index)
										this.$util.remove(this.replies, index)
										this.blog.comments = this.blog.comments.filter(c => list.every(
											r => r.id != c.id))
									} else {
										let children = this.getChildren(cmt, this.replies[index])
										children.push(cmt)
										this.replies[index] = this.replies[index].filter(r => children
											.every(c => c.id != r.id))
										this.blog.comments = this.blog.comments.filter(c => children
											.every(r => r.id != c.id))
									}
								}
							}, () => {
								uni.hideLoading()
							})
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},
			onLogin() {
				this.$refs.shell.show();
			},
			//点赞暂时不动
			changeGood(blog, isGood) {
				//同步到服务器,并且去最新数据
				let url = this.$params.host + (!isGood ? this.$params.action_good : this.$params
					.action_del_good);
				let data = {
					"id": blog.id,
				}
				this.$request.postParam(url, data, res => {
					this.blog.good = res.data;
					let blog_data = {
						"picture": blog.picture,
						"id": blog.id,
						"title": blog.title
					}
					if (isGood) {
						this.hasGood = !this.hasGood;
						this.good_ids.splice(this.good_ids.indexOf(blog_data), 1);
					} else {
						this.hasGood = !this.hasGood;
						this.good_ids.push(blog_data);
					}
					let pages = getCurrentPages();
					let pre = pages[pages.length - 2];
					pre.refreshGood(this.good_ids);
					uni.setStorageSync(this.$params.key_good_ids, this.good_ids);

				}, () => {

				});
			},

			// changeGood(id, isGood) {
			// 	let url = this.$params.host + (isGood ? this.$params.action_good : this.$params.action_del_good);
			// 	let data = {
			// 		"id": id,
			// 	}
			// 	this.$request.postParam(url, data, res => {
			// 		this.blog.good = res.data;
			// 		if (isGood) {
			// 			this.hasGood = true
			// 			//从缓存里获取数组
			// 			let arr = uni.getStorageSync(this.$params.key_good_ids) || [];
			// 			//把id添加到数组里
			// 			arr.push(id)
			// 			//把添加了blogid的数组重新放入缓存
			// 			uni.setStorageSync(this.$params.key_good_ids, arr)
			// 			//把hasgood变成true
			// 		} else {
			// 			//从缓存里获取数组
			// 			this.hasGood = false
			// 			// console.log(id);
			// 			let arr = uni.getStorageSync(this.$params.key_good_ids) || []
			// 			// 找到id对应的下标
			// 			let index = arr.indexOf(id)
			// 			// 删除该id
			// 			if (index !== -1) {
			// 				arr.splice(index, 1)
			// 				uni.setStorageSync(this.$params.key_good_ids, arr)
			// 			}
			// 		}

			// 		let count = res.data
			// 		console.log(count);
			// 		console.log(id);
			// 		this.$noti.post(this.$params.noti_refresh_good, {
			// 			id,
			// 			count
			// 		})
			// 	}, () => {

			// 	});
			// },
			addReadCount(id) {
				let url = this.$params.host + this.$params.action_read_count
				let data = {
					"id": id
				}
				this.$request.postParam(url, data, res => {
					let count = res.data
					//第一种方式，获取上一页面实实例
					// this.refreshPreviousPage(id, count)
					//第二种方式：使用通知中心
					this.$noti.post(this.$params.noti_refresh_count, {
						id,
						count
					})
				}, () => {

					this.getBlog(id)
				})
			},
			refreshPreviousPage(id, count) {
				let pages = getCurrentPages()
				let prev = pages[pages.length - 2]
				prev.refreshReadCount(id, count)
			},

			getBlog(id) {
				let url = this.$params.host + this.$params.action_blog + id
				this.$request.get(url, res => {
					this.loaded = true
					let blog = res.data
					uni.setNavigationBarTitle({
						title: blog.user.nickName
					})
					if (!blog.picture.startsWith("http")) {
						blog.picture = this.$params.host + blog.picture
					}
					blog.user.avatar = this.$params.host + blog.user.avatar
					blog.content = blog.content.replace(/\<img/gi, '<img class="img" ')
					blog.createTime = this.$util.formatTime(new Date(blog.createTime))
					this.blog = blog
					this.hasComment = true;
					this.formatComments(this.blog.comments)
				}, () => {})
			},
			formatComments(comments) {
				if (comments.length == 0) {
					return
				}
				let rootComments = []
				comments.forEach(c => {
					if (!c.avatar.startsWith("/http")) {
						c.avatar = this.$params.host + c.avatar.substring(1)
					}
					c.createTime = this.$util.formatTime(new Date(c.createTime))

					if (c.parentId == null) {
						rootComments.push(c)
					}
				})

				rootComments.sort((c1, c2) => {
					return new Date(c2.createTime).getTime() - new Date(c1.createTime).getTime();
				});
				let replies = new Array(rootComments.length).fill([]);
				let index = 0
				rootComments.forEach(r => {
					let cmmts = []
					cmmts = cmmts.concat(this.getChildren(r, comments))
					replies[index++] = cmmts
					comments = comments.filter(c => cmmts.every(cc => cc.id != c.id))
				})
				this.parents = rootComments
				this.replies = replies


			},
			getChildren(parent, comments) {
				//todo:得到parent所有的子评论

				let childrenComments = [];
				comments.forEach(comment => {
					if (parent.id == comment.parentId) {
						comment.toUser = parent.nickName;
						childrenComments.push(comment);
						let cmmts = comments.filter(cmt => cmt.id != comment.id)
						childrenComments.concat(this.getChildren(comment, cmmts));
					}
				})
				return childrenComments;
			},
			canDelete(item) {

				return app.globalData.ytpe == 1 || item.avatar == this.userAvatar
			},
			clickToReply(item) {
				parentId = item.id
				this.inputHolder = "@" + item.nickName
			},
			inputGetValue(e) {
				cmtValue = e.detail.value
			},
			pushCmtValue() {
				if (app.globalData.token.length == 0) {
					this.$refs.shell.show();
					return;
				}

				if (cmtValue.length == 0) {
					uni.showToast({
						title: "还没输入哦",
						icon: 'none',
					});
				}
				let data = {
					nick_name: app.globalData.nickName,
					avatar: "/" + app.globalData.avatar,
					email: app.globalData.email,
					content: cmtValue,
					blog_id: this.blog.id,
					parent_id: parentId,
					token: app.globalData.token,
					is_owner: app.globalData.uid == this.blog.user.id,
				}


				this.$request.post(this.$params.host + this.$params.action_blogs_add_comment, data, res => {
					if (!res.success) {
						uni.showToast({
							title: res.message,
							icon: "none"
						})

						return;
					}
					console.log(res);
					let cmt = {};
					console.log(cmt);
					cmt.avatar = res.data.avatar;
					cmt.blogId = res.data.blogId;
					cmt.content = res.data.content;
					cmt.createTime = res.data.createTime;
					cmt.email = res.data.email;
					cmt.id = res.data.id;
					cmt.nickName = res.data.nickName;
					cmt.owner = res.data.owner;
					cmt.parentId = res.data.parentId;
					let comments = this.blog.comments.concat(cmt);
					this.blog.comments = comments;
					this.formatComments(this.blog.comments)
					console.log(this.blog);
					this.hasComment = this.blog.comments.length > 0;
					this.inputHolder = "请输入评论......";
					this.inputValue = "";
					cmtValue = "";
					parentId = null;
					//刷新列表页的评论数
					this.cmtCount = this.blog.comments.length;
					this.$noti.post(this.$params.noti_refresh_comment_count, {
						id: this.blog.id,
						comments: comments,
					})

				}, () => {})

			},


			afterLogin() {
				console.log(getApp().globalData.avatar);
				this.userAvatar = this.$params.host + getApp().globalData.avatar;
				console.log(this.userAvatar);

			},
			popSheet(id){
							uni.showActionSheet({
								itemList: ["删除","收藏"],
								success: res => {
									if(res.tapIndex==0){
										uni.showModal({
											title: '删除',
											content: '确认吗',
											showCancel: true,
											cancelText: '取消',
											confirmText: '删除',
											success: res => {
												if(res.confirm) this.deleteBlog(id)
											},
											fail: () => {
												// console.log(failllll);
											},
											complete: () => {}
										});
									}else if(res.tapIndex == 1){
										uni.showToast({
											title:"已收藏"
										})
									}
								},
								fail: () => {},
								complete: () => {}
							});
						},
						deleteBlog(id){
							uni.showToast({
								title:"无权限！请登录"
							})
						},

	}
	}
</script>
<style>
	@import url("../blog/blog.css");
	@import url("../../common/iconfont.css");
</style>
